package com.crazy.cloud.common.xss;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;

/**
 * @program: share-project
 * @description: xss过滤
 * @author: CrazyMan
 * @create: 2018-05-11 17:50
 **/
public class XssDefenseFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        XssHttpServletRequestWraper wrappedRequest = new XssHttpServletRequestWraper((HttpServletRequest) servletRequest);
        if (!StringUtils.isEmpty(wrappedRequest.getContentType()) && wrappedRequest.getContentType().contains(MediaType.APPLICATION_JSON_VALUE)) {
            String body = IOUtils.toString(wrappedRequest.getReader());
            if (StringUtils.isNotBlank(body)) {
                wrappedRequest.resetInputStream(XssUtils.clearXss(body).getBytes());
                filterChain.doFilter(wrappedRequest, servletResponse);
            }
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
